<?php

/**
 *
 * @author Administrator
 *
 */
class Privilege_model extends MY_CI_Model
{
    protected $auto_login = FALSE;

    /**
     *
     * @access public
     *
     */
    public function __construct()
    {
        $this->table        = 'users';
        $this->primary_id   = 'id';
        $this->primary_name = 'mobile';

        parent::__construct();

    }

    public function set_auto_login($value = FALSE)
    {
        $this->auto_login = $value;
    }

    /**
     * 处理用户登录
     * @param string $admin_name
     * @param string $password
     * @return boolean
     */
    public function signin($admin_name, $password = NULL, $admin_id = 0)
    {
        $users = $this->check_user_name($admin_name, $admin_id);
        if ($users) {
            if ($users['active'] > 0) {
                if ($password == NULL || md5($password) == $users['password']) {
                    $this->set_session_cookie($users);
                    //更新登录信息
                    $this->update_login_info($users['id']);
                } else {
                    return ['error' => 1, 'message' => '登录密码不正确！'];
                }
            } else {
                return ['error' => 1, 'message' => '账号被禁止登陆！'];
            }
        } else {
            $log_item_id = $admin_id;
            $log_info    = sprintf("[%s]无效账号尝试登陆！", $admin_name);
            return ['error' => 1, 'message' => $log_info];
        }

        return ['error' => 0, 'message' => ''];
    }

    /**
     * 从cookie自动登录，验证校验码
     * @return boolean
     */
    public function cookie_auto_login()
    {
        $admin_name = $this->input->cookie('lcikp_name', TRUE);
        $adm_uhash  = $this->input->cookie('lcikp_key', TRUE);
        if (empty($admin_name) || empty($adm_uhash)) {
            $go_login = TRUE;
        }
        $users = $this->check_user_name($admin_name);
        if ($users && $this->verify_cookie_hash($users, $adm_uhash)) {
            $this->set_session_cookie($users);
            //更新登录信息
            $this->update_login_info($users['id']);
            $go_login = FALSE;
        } else {
            $go_login = TRUE;
        }
        return $go_login;
    }

    /**
     * 将用户登录信息写入session，cookie
     * @param unknown $admin_id
     * @param string $pwd
     */
    public function set_session_cookie($users)
    {

        $this->session->set_userdata('user_id', $users['id']);
        $this->session->set_userdata('mobile', $users['mobile']);
        $this->session->set_userdata('real_name', $users['real_name']);
        $this->session->set_userdata('avatar', $users['avatar']);//头像
        $this->session->set_userdata('sid', session_id());
        $this->session->set_userdata('ip', $_SERVER['REMOTE_ADDR']);

        // 角色权限
        $this->session->set_userdata('privilege_ids', $users['privilege_ids']);
        $this->session->set_userdata('is_web_admin_role', $users['is_web_admin_role']);

        if ($this->auto_login) {
            $cookie_time = (24 * 3600) * 7;
            $this->input->set_cookie("lcikp_name", $users['mobile'], $cookie_time);
            $this->input->set_cookie("lcikp_key", $this->generate_cookie_hash($users), $cookie_time);
        }
    }

    /**
     * 销毁用户登录信息
     */
    public function unset_session_cookie()
    {
        $this->session->unset_userdata('user_id');
        $this->session->unset_userdata('mobile');
        $this->session->unset_userdata('real_name');
        $this->session->unset_userdata('avatar');
        $this->session->unset_userdata('sid');
        //角色
        $this->session->unset_userdata('privilege_ids');
        $this->session->unset_userdata('is_web_admin_role');

        $this->input->set_cookie("lcikp_name", '', '');
        $this->input->set_cookie("lcikp_key", '', '');
        $this->input->set_cookie("lcikp_si", '', '');
        $this->input->set_cookie("lcikp_si", '', '');
    }



    /**
     * 检查用户名或手机号码是否存在
     * @param string $admin_name
     * @return array
     */
    public function check_user_name($admin_name, $admin_id = 0)
    {

        $this->db->select('*');
        $this->db->from($this->table . ' as a');
        if ($admin_id > 0) {
            $this->db->where("id", $admin_id);
        } else {
            $this->db->where("a.is_delete", 0);
            $this->db->where("a.mobile", $admin_name);
        }
        $users = $this->db->get()->row_array();

        // 多角色
        if (!empty($users)) {
            $this->db->select('privilege_ids, active');
            $this->db->from('role');
            $this->db->where('is_delete', 0);
            $this->db->where('active', 1);
            $this->db->where_in('id', explode(',', $users['web_role_id']));
            $role_list = $this->db->get()->result_array();
            if (empty($role_list)) {
                $privilege_ids = [];
            } else {
                $privilege_ids = '';
                foreach ($role_list as $k => $v) {
                    $privilege_ids = $privilege_ids . ',' . $v['privilege_ids'];
                }
                $privilege_ids = array_filter(array_unique(explode(',', $privilege_ids)));
            }
            $users['privilege_ids'] = $privilege_ids;
        }
        return $users;
    }

    /**
     * 更新登录信息
     * @param unknown $admin_id
     */
    public function update_login_info($admin_id)
    {
        $this->db->set('last_session', session_id());
        $this->db->set('last_time', time());
        $this->db->where('id', $admin_id);
        $this->db->update($this->table);
    }

    /**
     * 生成cookie验证码
     * @param unknown $users
     */
    public function generate_cookie_hash($users)
    {
        return md5(sprintf('%s@%s@%s', $users['id'], substr($users['password'], 8, 16),$users['avatar']));
    }

    /**
     * 验证cookie验证码
     * @param unknown $users
     */
    public function verify_cookie_hash($users, $key)
    {
        return $key === $this->generate_cookie_hash($users);
    }
}

?>